package croe.jdbc.dao;

import croe.jdbc.common.AppContextSupport;
import croe.jdbc.domain.ClassThreadLocal;
import croe.jdbc.domain.ParameterThreadLocal;
import croe.jdbc.utils.SqlUtils;
import org.apache.ibatis.session.SqlSession;

import java.io.Serializable;
import java.util.List;

/**
 * User: zengzhili
 * Date: 14-8-1
 * Time: 上午10:43
 */
public final class Dao {
    private static SqlSession sqlSession;

    static {
        sqlSession = (SqlSession) AppContextSupport.getAppContext().getBean("sqlSession");
    }

    public static <T> int insert(T t) {
        return DaoOperations.insert(t);
    }

    public static <T> int update(T t) {
        return DaoOperations.update(t);
    }

    public static <T> int delete(T t) {
        return DaoOperations.delete(t);
    }

    public static int delete(Class<?> clazz, Object... ids) {
        return DaoOperations.delete(clazz, ids);
    }

    public static <T> T load(final Class<T> clazz, Serializable id) {
        return DaoOperations.load(clazz, id);
    }

    public static <T> List<T> listAll(final Class<T> clazz) {
        return DaoOperations.listAll(clazz);
    }

    public static <T> int[] insertBath(List<T> dataList) {
        return DaoOperations.insertBath(dataList);
    }

    public static <T> int[] updateBath(List<T> dataList) {
        return DaoOperations.updateBath(dataList);
    }

    public static <T> int[] deleteBath(List<T> dataList) {
        return DaoOperations.deleteBath(dataList);
    }

    public static int executeUpdate(String sql, Object... parms) {
        if (SqlUtils.isSql(sql)) {
            return DaoOperations.executeUpdate(sql, parms);
        } else {
            return sqlSession.update(sql, parms);
        }
    }

    public static <T> T get(final Class<T> clazz, String sql, Object... parms) {
        if (SqlUtils.isSql(sql)) {
            return DaoOperations.get(clazz, sql, parms);
        } else {
            ClassThreadLocal.set(clazz);
            ParameterThreadLocal.set(parms);
            return (T) sqlSession.selectList(sql, parms).get(0);
        }
    }

    public static <T> List<T> listByKey(final Class<T> clazz, Object... primaryKey) {
        return DaoOperations.listByKey(clazz, primaryKey);
    }

    public static <T> List<T> listBySql(final Class<T> clazz, String sql, Object... parms) {
        if (SqlUtils.isSql(sql)) {
            return DaoOperations.listBySql(clazz, sql, parms);
        } else {
            ClassThreadLocal.set(clazz);
            ParameterThreadLocal.set(parms);
            return sqlSession.selectList(sql, parms);
        }
    }


}
